﻿
// actionFlag: 1 -> 新增；2 -> 修改；3 -> 查看
var actionFlag = getPar1("actionFlag");
var initFlag = getPar1("initFlag");         // 1 -> 手动结算; 0 -> 系统结算
var const_UserId = parent.parent._currentUserID;
var const_UserName = parent.parent._currentUserName;

var idList = "";

$(document).ready(function () {
    if (actionFlag == 1) {
        obj = $("#SystemGenNo");
        genNewSequenceNo(obj, "AccountsReceivable");

        $("#Rebate").val("100.00");
        $("#RebateAmount").val("0.00");
        $("#FactAmount").val("0.00");

        $("#GetARData").bind("click", function () { getARData(); });
        $("#CalcAR").bind("click", function () { calcAR(); });

        if (initFlag == 1) {
            $("#Amount").removeAttr("disabled");
            $("#Amount").val("0.00");
            $("#GetARData").hide();
            $("#CalcAR").hide();

            $("#contentdetail").hide();     // 手工结算录入时不需显示明细
        }
    }
    else {
        $("#GetARData").hide();
        $("#CalcAR").hide();

        //查看
        if (actionFlag == 3) {
            $("#AccountsReceivableNo").attr("disabled", "disabled");
            $("#SummaryDate").attr("disabled", "disabled");
            $("#CustomerNo").attr("disabled", "disabled");
            $("#CustomerName").attr("disabled", "disabled");
            $("#SumStartDate").attr("disabled", "disabled");
            $("#SumEndDate").attr("disabled", "disabled");
            $("#Rebate").attr("disabled", "disabled");
            $("#RebateAmount").attr("disabled", "disabled");
            $("#FactAmount").attr("disabled", "disabled");

            if (initFlag == 1) {
                $("#contentdetail").hide();     // 手工结算录入时不需显示明细
            }
        }
    }

    $("#Amount").numberbox({
        min: -999999999,
        precision: 2
    });

    $("#Rebate").numberbox({
        min: -999999999,
        precision: 2
    });

    $("#RebateAmount").numberbox({
        min: -999999999,
        precision: 2
    });

    $("#FactAmount").numberbox({
        min: -999999999,
        precision: 2
    });

    $("#Amount").bind("change", function () { calcFactAR(1); });
    $("#Rebate").bind("change", function () { calcFactAR(1); });
    $("#RebateAmount").bind("change", function () { calcFactAR(1); });
    $("#FactAmount").bind("change", function () { calcFactAR(2); });
});


var customSetEvent = function () {
    if (actionFlag == 3) {
        //debugger;
        if (initFlag == 0) {
            sumCondition = "AccountsReceivableNo = \'" + $("#AccountsReceivableNo").val() + "\'";
            src = "/Extend/YUIDataTableList.aspx?entity=V_BH_AccountsReceivableDetail&condition=" + sumCondition + "&order=EntryDate desc&hideToolbar=true&noDbClick=true";
            $("#ARDetailList").attr("src", src);
        }
    }
}

// 读取应收明细
var getARData = function () {
    if ($("#CustomerNo").attr("SValue") == "") {
        alert("客户编号不能为空!");
        $("#CustomerNo").focus();
        return;
    }

    if ($("#SumStartDate").val() == "") {
        alert("结算开始日期不能为空!");
        $("#SumStartDate").focus();
        return;
    }

    if ($("#SumEndDate").val() == "") {
        alert("结算结束日期不能为空!");
        $("#SumEndDate").focus();
        return;
    }

    sumCondition = "CustomerNo = \'" + $("#CustomerNo").attr("SValue") + "\' and ";
    sumCondition = sumCondition + "EntryDate >= \'" + $("#SumStartDate").val() + "\' and EntryDate <= \'" + $("#SumEndDate").val() + "\'";
    sumCondition = sumCondition + " and AccountsReceivableID = \'00000000-0000-0000-0000-000000000000\'"

    src = "/Extend/YUIDataTableList.aspx?entity=V_BH_AccountsReceivableDetail&condition=" + sumCondition + "&order=EntryDate desc&hideToolbar=true&noDbClick=true";
    $("#ARDetailList").attr("src", src);

    //$("#APDetailList").attr("src", "/Extend/YUIDataTableList.aspx?entity=V_BH_AccountsPayableDetail&condition=Amount>0&order=EntryDate desc&hideToolbar=true");
    //document.frames("APDetailList").location.reload();

}

// 计算应收总金额以及生成IDList
var calcAR = function () {
    var totalFactAR = 0;
    idList = "";
    arDetail = document.frames("ARDetailList");

    for (var i = 0; i < arDetail.mDataTable.getRecordSet()._records.length; i++) {
        curRecord = arDetail.mDataTable.getRecordSet()._records[i];
        idList = idList + (idList == "" ? "" : ",") + curRecord._oData.ID;
        totalFactAR = totalFactAR + parseFloat(curRecord._oData.Amount.toString());
    }

    $("#Amount").val(totalFactAR.toFixed(2));
    $("#FactAmount").val(totalFactAR.toFixed(2));
}

// 输入折扣率与折扣金额计算实付总金额
var calcFactAR = function (i) {
    amount = parseFloat($("#Amount").val());
    rebate = parseFloat($("#Rebate").val());     // 带百分号，实际值要除以100
    rebateAmount = parseFloat($("#RebateAmount").val());
    factAmount = parseFloat($("#FactAmount").val());

    if (i == 1) {
        $("#FactAmount").val((((amount * rebate) / 100) - rebateAmount).toFixed(2));
    }
    else if (i == 2) {
        $("#Rebate").val("100.00");
        $("#RebateAmount").val((Math.abs(factAmount - amount)).toFixed(2));
    }
}


// 检测应收单编号是否重复
var fnCheckARNo = function (val) {
    if (val != "") {
        var accountsReceivableNo = fnGetData("BH_AccountsReceivable", "ID<>'" + instance[0].ID.toString() + "' and AccountsReceivableNo='" + val + "'");
        if (accountsReceivableNo != null && accountsReceivableNo != "") {
            alert("收款单编号: [ " + val + " ] 已存在, 请重新输入!");
            setTimeout(function () {
                $("#AccountsReceivableNo").focus();
                $("#AccountsReceivableNo").val("");
            }, 10);
        }
    }
}

var getCompanyData = function (company) {
    return fnGetData("BH_Company", "CompanyNo='" + company + "' or CompanyName='" + company + "' or ShortName='" + company + "'");
}

// 设置客户名称
var setCompanyName = function () {
    var companyNo = $("#CustomerNo").attr("SValue");
    Company = getCompanyData(companyNo);

    if (Company == null || Company == "") {
        alert("客户：" + companyNo + " 还未定义!");
        $("#CustomerName").val("");
        $("#CustomerNo").focus();
        return;
    }

    $("#CustomerName").val(Company.rows[0].CompanyName);
}



// 提交检测
var fnCustomCheck = function () {
    if (instance[0].AccountsReceivableNo == "" || instance[0].AccountsReceivableNo == null) {
        $('#AccountsReceivableNo').focus();
        return "应收编号不能为空!";
    }
    if (instance[0].CustomerNo == "" || instance[0].CustomerNo == null) {
        $('#CustomerNo').focus();
        return "客户编号不能为空!";
    }
    if (instance[0].SummaryDate == "" || instance[0].SummaryDate == null) {
        $('#SummaryDate').focus();
        return "结算日期不能为空!";
    }
    if (instance[0].SumStartDate == "" || instance[0].SumStartDate == null) {
        $('#SumStartDate').focus();
        return "结算开始日期不能为空!";
    }
    if (instance[0].SumEndDate == "" || instance[0].SumEndDate == null) {
        $('#SummEndDate').focus();
        return "结算结束日期不能为空!";
    }

    return "";
}

var fnSetValue = function () {
    instance[0].AccountsReceivableNo = instance[0].AccountsReceivableNo.toUpperCase();
    instance[0].AddUser = const_UserId;
    if (actionFlag == "1") {
        var now = new Date();
        instance[0].AddTime = fnGetMyDate(now).toString();
        instance[0].InitFlag = initFlag;
    }
}

// 保存数据
var fnCustomSave = function () {

    fnSetValue();

    //initFlag = 0;

    dataAction = (actionFlag == "1") ? "A" : "C";
    //debugger;
    if (typeof (_DataTable) != "undefined") {
        if (fnCheckEmpty() == false) {
            alert("明细数据没有录入");
        }
        _DataTable.GetData();

        detailJson = $.toJSON(_DataTable.Rows).replace(/'/g, "[B]").replace(/\+/g, "[J]")
    }

    json = $.toJSON(instance[0]).replace(/'/g, "[B]").replace(/\+/g, "[J]");

    $.ajax({
        async: false, //异步请求
        cache: false, //不从浏览器缓存中加载
        type: "GET",
        /*dataType: "json",*/
        url: "/DCBH/DCBHCommonOperator.aspx",
        data: { Action: "procedure", entity: "V_BH_AccountsReceivable", initFlag: initFlag, jsonData: json, detailIDList: idList },
        success: function (data) {
            //debugger;
            if (data != "") {
                if (data == "1") {
                    alert("数据保存成功!");

                    if (parent.SaveAndAddNewFlag == true) {
                        location.href = location.href
                    }

                    if (parent.SaveSuccessClose == true) {
                        parent.parent.CloseCurPage();
                    }
                }
                else {
                    alert(data);
                }
            }
        },
        error: function (e) {
            alert("保存失败, 请联系开发人员，核查系统！");
            return;
        }
    });

}